﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

using KeePass.Plugins;
using KeePass.Forms;
using KeePass.Resources;

using KeePassLib;
using KeePassLib.Security;

// The namespace name must be the same as the filename of the
// plugin without its extension.
// For example, if you compile a plugin 'SamplePlugin.dll', the
// namespace must be named 'SamplePlugin'.

namespace KPSave2YaD
{
    /// <summary>
    /// This is the main plugin class. It must be named exactly
    /// like the namespace and must be derived from
    /// <c>KeePassPlugin</c>.
    /// </summary>
    public sealed class KPSave2YaDExt : Plugin

    {
        // The sample plugin remembers its host in this variable.
        private IPluginHost m_host = null;

        private ToolStripSeparator m_tsSeparator = null;
        private ToolStripMenuItem m_tsmiKPSave2YaDEntry = null;

        /// <summary>
        /// The <c>Initialize</c> function is called by KeePass when
        /// you should initialize your plugin (create menu items, etc.).
        /// </summary>
        /// <param name="host">Plugin host interface. By using this
        /// interface, you can access the KeePass main window and the
        /// currently opened database.</param>
        /// <returns>You must return <c>true</c> in order to signal
        /// successful initialization. If you return <c>false</c>,
        /// KeePass unloads your plugin (without calling the
        /// <c>Terminate</c> function of your plugin).</returns>
        public override bool Initialize(IPluginHost host)
        {
            Debug.Assert(host != null);
            if (host == null) return false;
            m_host = host;

            // Get a reference to the 'Tools' menu item container
            ToolStripItemCollection tsMenu = m_host.MainWindow.ToolsMenu.DropDownItems;

            // Add a separator at the bottom
            m_tsSeparator = new ToolStripSeparator();
            tsMenu.Add(m_tsSeparator);


            // Add menu item 'KPSave2YaD'
            m_tsmiKPSave2YaDEntry = new ToolStripMenuItem();
            m_tsmiKPSave2YaDEntry.Text = "KPSave2YaD";
            m_tsmiKPSave2YaDEntry.Click += OnMenuKPSave2YaDEntry;
            tsMenu.Add(m_tsmiKPSave2YaDEntry);

            // We want a notification when the user tried to save the
            // current database
            m_host.MainWindow.FileSaved += OnFileSaved;

            return true; // Initialization successful
        }

        /// <summary>
        /// The <c>Terminate</c> function is called by KeePass when
        /// you should free all resources, close open files/streams,
        /// etc. It is also recommended that you remove all your
        /// plugin menu items from the KeePass menu.
        /// </summary>
        public override void Terminate()
        {
            // Remove all of our menu items
            ToolStripItemCollection tsMenu = m_host.MainWindow.ToolsMenu.DropDownItems;
            tsMenu.Remove(m_tsSeparator);
            tsMenu.Remove(m_tsmiKPSave2YaDEntry);

            // Important! Remove event handlers!
            m_host.MainWindow.FileSaved -= OnFileSaved;
        }

        private void OnMenuKPSave2YaDEntry(object sender, EventArgs e)
        {
            if (!m_host.Database.IsOpen)
            {
                MessageBox.Show("You first need to open a database!", "KPSave2YaD");
                return;
            }

            // Create 10 groups
            for (int i = 0; i < 10; ++i)
            {
                // Create a new entry
                PwEntry pe = new PwEntry(true, true);

                // Set some of the string fields
                pe.Strings.Set(PwDefs.TitleField, new ProtectedString(false, "Sample Entry"));
                pe.Strings.Set(PwDefs.UserNameField, new ProtectedString(false,
                    Guid.NewGuid().ToString()));

                // Finally tell the parent group that it owns this entry now
                m_host.Database.RootGroup.AddEntry(pe, true);
            }

            m_host.MainWindow.UpdateUI(false, null, true, m_host.Database.RootGroup,
                true, null, true);
        }

        private void OnFileSaved(object sender, FileSavedEventArgs e)
        {
            MessageBox.Show("Notification received: the user has tried to save the current database to:\r\n" +
                m_host.Database.IOConnectionInfo.Path + "\r\n\r\nResult:\r\n" +
                (e.Success ? "Success" : "Failed"), "Sample Plugin",
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

    }
}
